package com.tt.action;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.tt.bean.UserBean;
import com.tt.dao.UserDaoImpl;
import com.tt.service.LoginServiceImpl;
import com.tt.utils.CaptchaUtil;
@Controller
@RequestMapping("/userL")
public class LoginAction {
	@Autowired
	LoginServiceImpl loginServiceImpl;
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ModelAndView login(UserBean userBean,HttpSession hs){
		ModelAndView mv = new ModelAndView();
		if(loginServiceImpl.login(userBean)){
			int errorCount = 0;
			UserBean one =loginServiceImpl.loginUserInfo(userBean);
			mv.addObject("userBean", one);
			mv.addObject("showUserInfo", 0);
			if(hs.getAttribute("errorCount") != null){
				errorCount = Integer.parseInt(hs.getAttribute("errorCount").toString());
			}
			if(errorCount <= 2 || errorCount == 0){
				mv.setViewName("HomePage");
				//mv.addObject("userBean", userBean);
			}else if(errorCount > 2){
				String code = hs.getAttribute("code").toString();
				if(userBean.getCode().equalsIgnoreCase(code)){
					mv.setViewName("HomePage");
					//mv.addObject("userBean", userBean);
				}else{
					mv.setViewName("Login");
					mv.addObject("ErrorInfo", "验证吗错误");	
				}
			}
			
		}else{
			if(hs.getAttribute("errorCount") == null || hs.getAttribute("errorCount") == ""){
				int errorCount = 0;
				hs.setAttribute("errorCount", errorCount);
			}else{
				int errorCount = Integer.parseInt(hs.getAttribute("errorCount").toString());
				hs.setAttribute("errorCount", ++errorCount);
			}
			mv.setViewName("Login");
			mv.addObject("ErrorInfo", "邮箱账号或密码错误");	
			
		}
		return mv;
	}
	@RequestMapping("/check")  
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {  
        response.setHeader("Expires", "-1");  
        response.setHeader("Cache-Control", "no-cache");  
        response.setHeader("Pragma", "-1");  
        CaptchaUtil util = CaptchaUtil.Instance();   
        String code = util.getString();  
        request.getSession().setAttribute("code", code);  
        ImageIO.write(util.getImage(), "jpg", response.getOutputStream());  
    } 
	@RequestMapping("/register") 
	public ModelAndView register(){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("Register");
		return mv;
	}
	@RequestMapping("/fp") 
	public ModelAndView forgetPWD(){
		ModelAndView mv = new ModelAndView();
		mv.setViewName("ForgetPWD");
		return mv;
	}
}
